package calvin.study.redis.controller;

import java.text.MessageFormat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import calvin.study.redis.service.RedisLockService;
import cn.hutool.core.util.IdUtil;

@RequestMapping("redis")
@Controller
public class RedisController {
	@Autowired
	RedisLockService redisLock;

	int count = 0;

	@RequestMapping("index")
	@ResponseBody
	public String index() throws InterruptedException {

		int clientcount = 1;// 1000个线程
		CountDownLatch countDownLatch = new CountDownLatch(clientcount);

		ExecutorService executorService = Executors.newFixedThreadPool(clientcount);
		long start = System.currentTimeMillis();
		for (int i = 0; i < clientcount; i++) {
			executorService.execute(() -> {
				// 通过Snowflake算法获取唯一的ID字符串
				String id = IdUtil.simpleUUID();
				try {
					//加锁
					redisLock.lock(id);
					//执行业务逻辑 ... 此时其他线程处于排队等候
					count++;
				} finally {
					//释放当前线程锁，等待下一线程执行。
					redisLock.unlock(id);
				}
				countDownLatch.countDown();
			});
		}
		countDownLatch.await();
		long end = System.currentTimeMillis();
		System.out.println(MessageFormat.format("执行线程数：{0}，总耗时：{1}，count数为：{2}", clientcount, end - start, count));
		return "Hello";
	}
}
